package com.school.dao;

import com.school.model.RechargeCode;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class RechargeCodeDao {

    private final JdbcTemplate jdbcTemplate;

    public RechargeCodeDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void save(RechargeCode rechargeCode) {
        String sql = "INSERT INTO RechargeCode (code, amount) VALUES (?, ?)";
        jdbcTemplate.update(sql, rechargeCode.getCode(), rechargeCode.getAmount());
    }

    public RechargeCode findByCode(String code) {
        String sql = "SELECT * FROM RechargeCode WHERE code = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{code}, (rs, rowNum) -> {
                RechargeCode rc = new RechargeCode();
                rc.setCode(rs.getString("code"));
                rc.setAmount(rs.getInt("amount"));
                rc.setUsed(rs.getBoolean("used"));
                return rc;
            });
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    public void markAsUsed(String code) {
        String sql = "UPDATE RechargeCode SET used = ? WHERE code = ?";
        jdbcTemplate.update(sql, true, code);
    }
}